package order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;

import common.model.*;
import common.model.cart.Cart;
import common.model.coupon.Coupon;
import common.model.goods.Sku;
import common.model.goods.Spu;
import common.model.order.OrderItem;
import common.model.order.Orders;
import common.model.order.SalesSummary;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import order.mapper.OrderMapper;
import order.mapper.SalesSummaryMapper;
import order.mq.DelayMessageProcessor;
import order.service.CartServiceFeignClient;
import order.service.IOrderService;
import order.service.GoodsServiceFeignClient;
import common.dto.userdto.AddressDTO;
import common.dto.orderdto.OrderDTO;
import common.dto.orderdto.OrderDetail;
import common.dto.orderdto.OrderItemDTO;
import common.dto.orderdto.SalesTrend;
import order.mapper.OrderItemMapper;
import order.service.CouponServiceFeignClient;
import order.service.ShopServiceFeignClient;
import common.dto.goodsdto.SkuDTO;
import common.dto.goodsdto.SpuDTO;
import common.dto.orderdto.Logistics;
import common.dto.shopdto.ShopDTO;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import common.utils.MqConstants;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private CartServiceFeignClient cartServiceFeignClient;
    @Autowired
    private GoodsServiceFeignClient goodsServiceFeignClient;
    @Autowired
    private CouponServiceFeignClient couponServiceFeignClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SalesSummaryMapper salesSummaryMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ShopServiceFeignClient shopServiceFeignClient;

    //创建订单
    @Override
    @Transactional
    public Result createOrder(Long uid, AddressDTO addressDTO, List<String> cartIds, List<String> couponCodes) {
        // 生成订单号
        LocalDateTime now = LocalDateTime.now();
        String orderNo = "OD" + now.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + 
                        "B" + String.format("%06d", orderMapper.findOrderCountByUid(uid));
        // 1. 查询购物车
        Result res = cartServiceFeignClient.subCartlist(uid, cartIds);
        if (res.getCode() != 200) {
            return Result.failure(ResultCodeEnum.FAIL, "购物车服务异常");
        }
        
        // 2. 获取购物车中的商品
        List<Cart> carts = JSON.parseArray(JSON.toJSONString(res.getData()), Cart.class);
        if (carts.isEmpty()) {
            return Result.failure(ResultCodeEnum.FAIL, "结算清单为空");
        }

        // 3. 检查商品库存
        for (Cart cart : carts) {
            Result goodsResult = goodsServiceFeignClient.getSkuById(cart.getSkuId());
            if (goodsResult.getCode() != 200) {
                return Result.failure(ResultCodeEnum.FAIL, "商品服务异常");
            }
            
            Sku sku = JSON.parseObject(JSON.toJSONString(goodsResult.getData()), Sku.class);
            System.out.println("sku: " + sku.getStock());
            if (sku.getStock() < cart.getQuantity()) {
                return Result.failure(ResultCodeEnum.FAIL, sku.getSpecs() + "库存不足");
            }
        }
        
        // 5. 处理优惠券
        BigDecimal discountAmount = BigDecimal.ZERO;
        if (couponCodes != null && !couponCodes.isEmpty()) {
            Result couponResult = couponServiceFeignClient.getCouponByCode(couponCodes,uid,orderNo);
            System.out.println("couponResult: " + couponResult);
            if (couponResult.getCode() != 200) {
                return Result.failure(ResultCodeEnum.FAIL, "优惠券服务异常");
            }
            
            List<Coupon> coupons = JSON.parseArray(JSON.toJSONString(couponResult.getData()), Coupon.class);
            for (Coupon coupon : coupons) {
               discountAmount = discountAmount.add(coupon.getValue());
            }
        }

        // 4. 扣减库存
        for (Cart cart : carts) {
            Result goodsResult = goodsServiceFeignClient.getSkuById(cart.getSkuId());
            if (goodsResult.getCode() != 200) {
                throw new RuntimeException("商品服务异常");
            }
            
            Sku sku = JSON.parseObject(JSON.toJSONString(goodsResult.getData()), Sku.class);
            sku.setStock(sku.getStock() - cart.getQuantity());
            Result updateResult = goodsServiceFeignClient.updateSku(sku);
            if (updateResult.getCode() != 200) {
                throw new RuntimeException("更新库存失败");
            }
        }

       

        // 6. 创建订单
        Orders order = new Orders();
        
        order.setOrderNo(orderNo);
        order.setUserId(uid);//用户id
        order.setProvince(addressDTO.getProvince());//省
        order.setCity(addressDTO.getCity());//市
        order.setDistrict(addressDTO.getDistrict());//区
        order.setAddressDetail(addressDTO.getAddressDetail());//详细地址
        order.setPostalCode(addressDTO.getPostalCode());//邮编
        order.setRecipientPhone(addressDTO.getTelephone());//收货人电话
        order.setRecipientName(addressDTO.getRecipientName());//收货人姓名

         
        // 计算商品总价
        BigDecimal itemAmount = carts.stream()
                .map(cart -> new BigDecimal(cart.getPromotionPrice()).multiply(BigDecimal.valueOf(cart.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 设置订单金额
        order.setItemAmount(itemAmount);//商品总价
        order.setDiscountAmount(discountAmount);//优惠金额
        order.setFreightAmount(BigDecimal.ZERO); // TODO 运费，可以根据实际情况计算
        order.setPayAmount(itemAmount.subtract(discountAmount));//支付金额
        order.setTotalAmount(itemAmount);//订单总价
        
        // 设置订单状态
        order.setStatus(0);
        order.setPaymentStatus(0);
        
        
        
        // 设置时间
        order.setCreateTime(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        order.setUpdateTime(now);
        
        // 7. 保存订单
        orderMapper.insertOrder(order);
        
        // 8. 保存订单项
        for (Cart cart : carts) {
            // 获取SKU信息
            Result skuResult = goodsServiceFeignClient.getSkuById(cart.getSkuId());
            if (skuResult.getCode() != 200) {
                throw new RuntimeException("获取商品信息失败");
            }
            Sku sku = JSON.parseObject(JSON.toJSONString(skuResult.getData()), Sku.class);
            
            // 获取SPU信息
            Result spuResult = goodsServiceFeignClient.getSpuById(cart.getSpuId());
            if (spuResult.getCode() != 200) {
                throw new RuntimeException("获取商品信息失败");
            }
            Spu spu = JSON.parseObject(JSON.toJSONString(spuResult.getData()), Spu.class);
            
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(order.getOrderNo());
            orderItem.setSkuId(cart.getSkuId());
            orderItem.setSpuId(cart.getSpuId());
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setPrice(new BigDecimal(cart.getPromotionPrice()));
            orderItem.setTotalPrice(new BigDecimal(cart.getPromotionPrice()).multiply(BigDecimal.valueOf(cart.getQuantity())));
            orderItem.setItemName(spu.getTitle() + " " + sku.getSpecs());
            orderItem.setItemImage(sku.getMainImage());
            orderMapper.insertOrderItem(orderItem);
        }

        // 9. 从购物车中移除已下单的商品
        cartServiceFeignClient.deleteCartlist(uid, cartIds);

        // 10. 发送延迟消息检查订单状态
        try {
            MulitiDelayMessage<Long> message = MulitiDelayMessage.of(order.getId(),
             5000L, 5000L, 5000L, 5000L, 10000L, 10000L,
             10000L, 10000L, 30000L, 30000L, 60000L, 60000L, 120000L, 120000L, 120000L);//一共10分钟，时间队列由小到大排列
            rabbitTemplate.convertAndSend(
                MqConstants.DELAY_EXCHANGE,
                MqConstants.DELAY_BINDING_KEY,
                message,
                new DelayMessageProcessor(message.removeDelayTime().intValue())
            );
        } catch (Exception e) {
            throw new RuntimeException("延迟消息发送失败: " + e.getMessage());
        }

        return Result.success(order);
    }
    //获取用户订单列表
    @Override
    public Result getOrders(Long uid) {
        //1.判断uid是否为空
        if (uid == null) {
            return Result.failure(ResultCodeEnum.FAIL,"用户id为空");
        }
        //2.根据uid查询订单
        List<Orders> orders = orderMapper.findOrderByUid(uid);
        List<OrderDTO> orderDTOs = new ArrayList<>();
        for (Orders order : orders) {
            //根据订单编号查询订单项
            List<OrderItem> orderItems = orderMapper.findOrderItemsByOrderNo(order.getOrderNo());
            //将订单项转换为OrderItemDTO
            List<OrderItemDTO> orderItemDTOs = orderItems.stream().map(orderItem -> {
                OrderItemDTO orderItemDTO = new OrderItemDTO();
                BeanUtils.copyProperties(orderItem, orderItemDTO);
                orderItemDTO.setOrderNo(order.getOrderNo());
                return orderItemDTO;
            }).collect(Collectors.toList());
            //将订单转换为OrderDTO
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(order, orderDTO);
            orderDTO.setOrderItemList(orderItemDTOs);
            orderDTOs.add(orderDTO);
        }
        return Result.success(orderDTOs);
    }
    //根据订单id查询订单详情
    @Override
    public Result getOrderById(Long orderId) {
        //1.判断id是否为空
        if (orderId == null) {
            return Result.failure(ResultCodeEnum.FAIL,"订单id为空");
        }
        //2.根据id查询订单
        Orders order = orderMapper.findOrderById(orderId);
        //判断订单是否为空
        if (order == null) {
            return Result.failure(ResultCodeEnum.FAIL,"订单为空");
        }
        //根据订单编号查询订单项
        List<OrderItem> orderItems = orderMapper.findOrderItemsByOrderNo(order.getOrderNo());
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrder(order);
        orderDetail.setOrderItems(orderItems);
        //4.返回订单
        return Result.success(orderDetail);
    }
    //根据订单状态查询用户订单
    @Override
    public Result getOrdersByStatus(Integer status, Long uid) {
        //1.判断status是否为空
        if (status == null) {
            return Result.failure(ResultCodeEnum.FAIL,"订单状态为空");
        }
        //2.根据status查询订单
        List<Orders> orders = orderMapper.findOrderByStatus(status, uid);
        List<OrderDTO> orderDTOs = new ArrayList<>();
        for (Orders order : orders) {
            //根据订单编号查询订单项
            List<OrderItem> orderItems = orderMapper.findOrderItemsByOrderNo(order.getOrderNo());
            //将订单项转换为OrderItemDTO
            List<OrderItemDTO> orderItemDTOs = orderItems.stream().map(orderItem -> {
                OrderItemDTO orderItemDTO = new OrderItemDTO();
                BeanUtils.copyProperties(orderItem, orderItemDTO);
                orderItemDTO.setOrderNo(order.getOrderNo());
                return orderItemDTO;
            }).collect(Collectors.toList());
            //将订单转换为OrderDTO  
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(order, orderDTO);
            orderDTO.setOrderItemList(orderItemDTOs);
            orderDTOs.add(orderDTO);
        }

        //3.返回订单
        return Result.success(orderDTOs);
    }
    //订单支付成功
    @Override
    public Result payOrder(String orderNo) {
        //获取订单
        Orders orders = orderMapper.selectOne(new LambdaQueryWrapper<Orders>().eq(Orders::getOrderNo, orderNo));
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取当前周
        int weekOfYear = LocalDateTime.now().get(WeekFields.ISO.weekOfYear());
        //获取当前星期
        int dayOfWeek = LocalDateTime.now().get(WeekFields.ISO.dayOfWeek());
        //获取当前年
        int year = LocalDateTime.now().getYear();
        //获取当前月
        int month = LocalDateTime.now().getMonthValue();
        // 支付订单
        orderMapper.updateOrderStatus(orders.getId(), 1, now);
        //生成销售记录数据
        //获取订单
        Orders order = orderMapper.findOrderById(orders.getId());
        //获取订单项
        List<OrderItem> orderItems = orderMapper.findOrderItemsByOrderNo(order.getOrderNo());
        
        // 更新周销量记录
        updateSalesSummary("week_day", String.valueOf(dayOfWeek), 
                String.format("%d%02d", year, weekOfYear), order, orderItems);
        
        // 更新月销量记录
        updateSalesSummary("month", String.valueOf(month), 
                String.format("%d%02d", year, month), order, orderItems);
        
        // 更新年销量记录
        updateSalesSummary("year_month", String.valueOf(year), 
                String.valueOf(year), order, orderItems);
        
        return Result.success();
    }
    
    /**
     * 更新销售记录
     * @param timeDimension 时间维度
     * @param dimensionValue 维度值
     * @param timeRange 时间范围
     * @param order 订单
     * @param orderItems 订单项
     */
    private void updateSalesSummary(String timeDimension, String dimensionValue, 
            String timeRange, Orders order, List<OrderItem> orderItems) {
        // 查询销售记录，增加dimensionValue作为查询条件
        SalesSummary salesSummary = salesSummaryMapper.selectOne(
            new LambdaQueryWrapper<SalesSummary>()
                .eq(SalesSummary::getTimeRange, timeRange)
                .eq(SalesSummary::getTimeDimension, timeDimension)
                .eq(SalesSummary::getDimensionValue, dimensionValue)
        );
        
        // 如果不存在，则创建新记录
        if(salesSummary == null) {
            salesSummary = new SalesSummary();
            salesSummary.setTimeDimension(timeDimension);
            salesSummary.setDimensionValue(dimensionValue);
            salesSummary.setTimeRange(timeRange);
            salesSummary.setTotalSales(order.getPayAmount() != null ? order.getPayAmount() : BigDecimal.ZERO);
            salesSummary.setTotalOrders(1);
            salesSummary.setTotalItems(orderItems.size());
            salesSummaryMapper.insert(salesSummary);
        } else {
            // 如果存在，则更新记录
            BigDecimal currentSales = salesSummary.getTotalSales() != null ? salesSummary.getTotalSales() : BigDecimal.ZERO;
            BigDecimal orderAmount = order.getPayAmount() != null ? order.getPayAmount() : BigDecimal.ZERO;
            
            // 使用update方法而不是updateById
            SalesSummary updateSummary = new SalesSummary();
            updateSummary.setTotalSales(currentSales.add(orderAmount));
            updateSummary.setTotalOrders(salesSummary.getTotalOrders() + 1);
            updateSummary.setTotalItems(salesSummary.getTotalItems() + orderItems.size());
            
            salesSummaryMapper.update(updateSummary, new LambdaUpdateWrapper<SalesSummary>()
                .eq(SalesSummary::getTimeRange, timeRange)
                .eq(SalesSummary::getTimeDimension, timeDimension)
                .eq(SalesSummary::getDimensionValue, dimensionValue));
        }
    }
    //模拟订单发货
    @Override
    public Result shipOrder(Long orderId) {
        //查询订单
        Orders order = orderMapper.findOrderById(orderId);
        //判断订单是否为空
        if (order == null) {
            return Result.failure(ResultCodeEnum.FAIL, "订单为空");
        }
        //判断订单状态
        if (order.getStatus() != 1) {
            return Result.failure(ResultCodeEnum.FAIL, "订单未支付");
        }
        //判断订单是否已发货
        if (order.getStatus() == 2) {
            return Result.failure(ResultCodeEnum.FAIL, "订单已发货");
        }
        //判断订单是否已取消
        if (order.getStatus() == 4) {
            return Result.failure(ResultCodeEnum.FAIL, "订单已取消");
        }
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 更新订单状态和发货时间
        order.setStatus(2);
        order.setDeliveryTime(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        orderMapper.updateById(order);
        return Result.success();
    }

    //模拟订单收货
    @Override
    public Result finishOrder(Long orderId) {
        //查询订单
        Orders order = orderMapper.findOrderById(orderId);
        //判断订单是否为空
        if (order == null) {
            return Result.failure(ResultCodeEnum.FAIL, "订单为空");
        }
        //判断订单状态
        if (order.getStatus() != 2) {
            return Result.failure(ResultCodeEnum.FAIL, "订单未发货");
        }
        //判断订单是否已取消
        if (order.getStatus() == 4) {
            return Result.failure(ResultCodeEnum.FAIL, "订单已取消");
        }
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //更新订单状态和收货时间
        order.setStatus(3);
        order.setReceiveTime(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        orderMapper.updateById(order);

        return Result.success();
    }
    //模拟订单取消
    @Override
    public Result cancelOrder(Long id) {
        //判断是否已支付
        Orders order = orderMapper.findOrderById(id);
        if (order.getPaymentStatus() == 1) {
            // TODO 模拟退款
        }
        //判断是否已发货
        if (order.getStatus() == 2) {
            // TODO 模拟呼停物流
        }
        // 取消订单
        orderMapper.updateOrderStatus(id, 4, LocalDateTime.now());
        // 恢复库存
        // 获取订单项
        List<OrderItem> orderItems = orderMapper.findOrderItemsByOrderNo(order.getOrderNo());
        // 恢复库存
        for (OrderItem orderItem : orderItems) {
            //获取商品id
            Long skuId = orderItem.getSkuId();
            //获取商品
            Result skuResult = goodsServiceFeignClient.getSkuById(skuId);
            if (skuResult.getCode() != 200) {
                throw new RuntimeException("商品服务异常");
            }
            //将res中的数据转换为Sku对象
            Sku sku = JSON.parseObject(JSON.toJSONString(skuResult.getData()), Sku.class);
            //恢复库存
            sku.setStock(sku.getStock() + orderItem.getQuantity());
            //更新商品
            goodsServiceFeignClient.updateSku(sku);
        }
        return Result.success();
    }
    //删除订单
    @Override
    public Result deleteOrder(Long oid) {
        orderMapper.deleteById(oid);
        return Result.success();
    }
    //根据时间单位获取销售趋势数据
    @Override
    public Result getSalesTrend(String timeUnit) {
        //1.判断timeUnit是否为空
        if (timeUnit == null) {
            return Result.failure(ResultCodeEnum.FAIL,"时间单位为空");
        }
        
        List<SalesTrend> salesTrends = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        String timeRange;//时间范围
        
        // 根据不同的时间单位查询销售数据
        if ("week".equals(timeUnit)) {//周
            //获取当前周
            int weekOfYear = LocalDateTime.now().get(WeekFields.ISO.weekOfYear());
            // 查询本周数据，格式如：202521（2025年第21周）
            timeRange = String.format("%d%02d", year, weekOfYear);
            System.out.println("timeRange: " + timeRange);  
            
            try {
                // 查询周维度的销售数据
                List<SalesSummary> weeklySales = salesSummaryMapper.selectList(
                    new LambdaQueryWrapper<SalesSummary>()
                        .eq(SalesSummary::getTimeDimension, "week_day")
                        .eq(SalesSummary::getTimeRange, timeRange)
                        .orderByAsc(SalesSummary::getDimensionValue)
                );
                
                System.out.println("查询到的周数据条数: " + weeklySales.size());
                
                // 打印查询到的所有数据
                for (SalesSummary sale : weeklySales) {
                    System.out.println("周数据: dimensionValue=" + sale.getDimensionValue() + 
                                      ", totalSales=" + sale.getTotalSales() + 
                                      ", timeDimension=" + sale.getTimeDimension() +
                                      ", timeRange=" + sale.getTimeRange());
                }
                
                // 创建一个Map来存储每天的销售数据
                Map<String, BigDecimal> salesByDay = new HashMap<>();
                for (SalesSummary sale : weeklySales) {
                    salesByDay.put(sale.getDimensionValue(), sale.getTotalSales());
                }
                
                // 确保返回完整的7天数据
                for (int day = 1; day <= 7; day++) {
                    String dayStr = String.valueOf(day);
                    SalesTrend trend = new SalesTrend();
                    String dayOfWeek = getDayOfWeekName(day);
                    trend.setDate(dayOfWeek);
                    
                    // 如果有数据则使用实际销售额，否则设为0
                    BigDecimal sales = salesByDay.getOrDefault(dayStr, BigDecimal.ZERO);
                    trend.setSales(sales.intValue());
                    
                    salesTrends.add(trend);
                    System.out.println("添加周数据: " + dayOfWeek + " - " + sales);
                }
            } catch (Exception e) {
                System.err.println("查询周数据出错: " + e.getMessage());
                e.printStackTrace();
                
                // 出错时也返回7天的空数据
                for (int day = 1; day <= 7; day++) {
                    SalesTrend trend = new SalesTrend();
                    trend.setDate(getDayOfWeekName(day));
                    trend.setSales(0);
                    salesTrends.add(trend);
                }
            }
        } else if ("month".equals(timeUnit)) {//月
            // 查询本月数据，格式如：202505（2025年5月）
            timeRange = String.format("%d%02d", year, month);
            
            // 查询月维度的销售数据
            List<SalesSummary> monthlySales = salesSummaryMapper.selectList(
                new LambdaQueryWrapper<SalesSummary>()
                    .eq(SalesSummary::getTimeDimension, "day")
                    .eq(SalesSummary::getTimeRange, timeRange)
                    .orderByAsc(SalesSummary::getDimensionValue)
            );
            
            // 转换为销售趋势数据
            for (SalesSummary sale : monthlySales) {
                SalesTrend trend = new SalesTrend();
                // 格式化为 "MM-DD"
                trend.setDate(String.format("%02d-%s", month, sale.getDimensionValue()));
                trend.setSales(sale.getTotalSales().intValue());
                salesTrends.add(trend);
            }
        } else if ("year".equals(timeUnit)) {
            // 查询本年数据，格式如：2025
            timeRange = String.valueOf(year);
            
            // 查询年维度的销售数据
            List<SalesSummary> yearlySales = salesSummaryMapper.selectList(
                new LambdaQueryWrapper<SalesSummary>()
                    .eq(SalesSummary::getTimeDimension, "year_month")
                    .eq(SalesSummary::getTimeRange, timeRange)
                    .orderByAsc(SalesSummary::getDimensionValue)
            );
            
            // 转换为销售趋势数据
            for (SalesSummary sale : yearlySales) {
                SalesTrend trend = new SalesTrend();
                // 将维度值（1-12）转换为月份名称
                String monthName = getMonthName(Integer.parseInt(sale.getDimensionValue()));
                trend.setDate(monthName);
                trend.setSales(sale.getTotalSales().intValue());
                salesTrends.add(trend);
            }
        } else {
            return Result.failure(ResultCodeEnum.FAIL, "不支持的时间单位");
        }
        
        return Result.success(salesTrends);
    }
    
    /**
     * 获取周几的名称
     * @param dayOfWeek 周几（1-7）
     * @return 周几的名称
     */
    private String getDayOfWeekName(int dayOfWeek) {
        switch (dayOfWeek) {
            case 1: return "周一";
            case 2: return "周二";
            case 3: return "周三";
            case 4: return "周四";
            case 5: return "周五";
            case 6: return "周六";
            case 7: return "周日";
            default: return "未知";
        }
    }
    
    /**
     * 获取月份名称
     * @param month 月份（1-12）
     * @return 月份名称
     */
    private String getMonthName(int month) {
        switch (month) {
            case 1: return "一月";
            case 2: return "二月";
            case 3: return "三月";
            case 4: return "四月";
            case 5: return "五月";
            case 6: return "六月";
            case 7: return "七月";
            case 8: return "八月";
            case 9: return "九月";
            case 10: return "十月";
            case 11: return "十一月";
            case 12: return "十二月";
            default: return "未知";
        }
    }
    //获取最近的10条订单
    @Override
    public Result getRecentOrders() {
        List<Orders> orders = orderMapper.findRecentOrders();
        return Result.success(orders);
    }
    //获取订单列表
    @Override
    public Result getOrdersList() {
        List<Orders> orders = orderMapper.selectList(null); 
        return Result.success(orders);
    }

    //根据spuId查询订单id
    @Override
    public Result getOrderIdBySpuId(Long userId, Long spuId) {
        //参数校验
        if (userId == null || spuId == null) {
            return Result.failure(ResultCodeEnum.FAIL, "参数不能为空");
        }
        
        try {
            // 查询用户是否购买过此商品
            String orderNo = orderItemMapper.findOrderNoByUserIdAndSpuId(userId, spuId);
            
            if (orderNo == null || orderNo.isEmpty()) {
                // 用户未购买过此商品
                return Result.success(null);
            }
            
            // 查询对应的订单ID
            Orders order = orderMapper.selectOne(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getOrderNo, orderNo)
                .eq(Orders::getUserId, userId));
            
            if (order == null) {
                return Result.success(null);
            }
            
            return Result.success(order.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure(ResultCodeEnum.FAIL, "查询订单失败");
        }
    }

    //根据订单项id获取物流信息
    @Override
    public Result getLogisticsByOrderItemId(Long orderItemId) {
        // 参数校验
        if (orderItemId == null) {
            return Result.failure(ResultCodeEnum.FAIL, "订单项ID不能为空");
        }
        
        try {
            // 查询订单项
            OrderItem orderItem = orderItemMapper.selectById(orderItemId);
            if (orderItem == null) {
                return Result.failure(ResultCodeEnum.FAIL, "订单项不存在");
            }
            
            // 创建物流信息对象
            Logistics logistics = new Logistics();
            
            // 根据spuId查询spu
            Result spuResult = goodsServiceFeignClient.getSpuById(orderItem.getSpuId());
            if (spuResult.getCode() != 200) {
                return Result.failure(ResultCodeEnum.FAIL, "获取商品信息失败");
            }
            SpuDTO spuDTO = objectMapper.convertValue(spuResult.getData(), SpuDTO.class);
            logistics.setSpuDTO(spuDTO);
            
            // 根据skuId查询sku
            Result skuResult = goodsServiceFeignClient.getSkuById(orderItem.getSkuId());
            if (skuResult.getCode() != 200) {
                return Result.failure(ResultCodeEnum.FAIL, "获取商品规格信息失败");
            }
            SkuDTO skuDTO = objectMapper.convertValue(skuResult.getData(), SkuDTO.class);
            logistics.setSkuDTO(skuDTO);
            
            // 根据spu中的shopId查询店铺
            Result shopResult = shopServiceFeignClient.getShopById(spuDTO.getShopId());
            if (shopResult.getCode() != 200) {
                return Result.failure(ResultCodeEnum.FAIL, "获取店铺信息失败");
            }
            ShopDTO shopDTO = objectMapper.convertValue(shopResult.getData(), ShopDTO.class);
            logistics.setShopDTO(shopDTO);
            
            return Result.success(logistics);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure(ResultCodeEnum.FAIL, "获取物流信息失败: " + e.getMessage());
        }
    }
}
